<script lang="ts" setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

import { orgGetService, orgCreateService, orgUpdateService, orgDeleteService } from '../../../api/property.js';

// 初始化参数
// 按姓名模糊搜索、分页
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 区块、员工（负责人）
let orgData = ref([])
// 新增、编辑弹出层的显示/隐藏控制
let createDialog = ref(false)
let editDialog = ref(false)
// 级联选择框参数
const cascaderProps = {
    expandTrigger: 'hover' as const,
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'name',
}
// 用于创建org的响应式对象
let createForm = ref({
    name: null,
    dutyPersonName: null,
    dutyPersonPhone: null,
    propertyNumber: null,
    parentId: 0,
    status: '',
});
// 用于编辑org的响应式对象
let editForm = ref({
    name: null,
    dutyPersonName: null,
    dutyPersonPhone: null,
    propertyNumber: null,
    parentId: null,
    status: '',
});
// 点击编辑时，数据回显
const editDataTransfer = function (row) {
    editForm.value = row;
    editForm.value.status = editForm.value.status.toString();
}
async function getOrg() {
    try {
        let result = await orgGetService(search.value, currentPage.value, pageSize.value)
        if (result.code == 200) {
            orgData.value = result.data.list;
            total.value = result.data.total;
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常（getOrg）')
        console.log(error)
    }
}
getOrg();
async function createOrg() {
    try {
        let result = await orgCreateService(createForm.value)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            createDialog.value = false
            getOrg();
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login'});
        }
    } catch (error) {
        ElMessage.error('系统异常（createOrg）')
        console.log(error)
    }
}
async function editOrg() {
    try {
        let result = await orgUpdateService(editForm.value)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            editDialog.value = false
            getOrg();
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login'});
        }
    } catch (error) {
        ElMessage.error('系统异常（editOrg）')
        console.log(error)
    }
}
async function deleteOrg(orgId) {
    try {
        let result = await orgDeleteService(orgId)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            getOrg();
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login'});
        }
    } catch (error) {
        ElMessage.error('系统异常（deleteOrg）')
        console.log(error)
    }
}

</script>

<template>
    <!-- 头部 搜索、新增 区域 -->
    <el-row :gutter="20" class="header">
        <el-col :span="6">
            <el-input v-model="search" placeholder="请输入组织名称" clearable>
                <template #append>
                    <el-button @click="getOrg"> 搜索 </el-button>
                </template>
            </el-input>
        </el-col>
        <el-col :span="6">
            <el-button type="primary" @click="createDialog = true">新增</el-button>
        </el-col>
    </el-row>

    <!-- 华丽的分割线 -->
    <el-divider />

    <!-- 树形表格形式展示org数据 -->
    <el-table :data="orgData" row-key="id" style="width: 100%">
        <el-table-column prop="id" label="编号" width="100" v-if="false" />
        <el-table-column prop="name" label="组织名称" width="150" />
        <el-table-column prop="dutyPersonName" label="组织负责人" width="100">
            <template #default="{ row }">
                <el-tag v-if="row.dutyPersonName != null && row.dutyPersonName != ''">{{ row.dutyPersonName }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="dutyPersonPhone" label="负责人电话" width="120" />
        <el-table-column prop="propertyNumber" label="所辖房产数" width="100" />
        <el-table-column prop="parentName" label="父级" width="100">
            <template #default="{ row }">
                <span v-if="row.parentName == null">/</span>
                <span v-else>{{ row.parentName }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="180" />
        <el-table-column prop="status" label="状态" width="110">
            <template #default="{ row }">
                <el-tag v-if="row.status == 0" type="danger">停用</el-tag>
                <el-tag v-if="row.status == 1" type="success">启用</el-tag>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="120">
            <template #="rs">
                <el-button link type="primary" size="small"
                    @click="editDialog = true; editDataTransfer(rs.row)">编辑</el-button>
                <!-- 删除确认框 -->
                <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" @confirm="deleteOrg(rs.row.id)"
                    icon-color="#F56C6C" title="确认删除这个组织？">
                    <template #reference>
                        <el-button link type="primary" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>

    <!-- 底部分页器 -->
    <div v-if="total > 0 && (search != null && search != '')">
        <div class="page-box">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
                :small="true" :disabled="false" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="getOrg" @current-change="getOrg" />
        </div>
    </div>

    <!-- 新增区块的弹出层 -->
    <el-dialog v-model="createDialog" title="新增组织" width="32%">
        <el-form :model="createForm">
            <el-form-item label="组织名称">
                <el-input v-model="createForm.name" placeholder="请输入组织名称" />
            </el-form-item>
            <el-form-item label="组织负责人">
                <el-input v-model="createForm.dutyPersonName" placeholder="请输入负责人名称" />
            </el-form-item>
            <el-form-item label="负责人电话">
                <el-input v-model="createForm.dutyPersonPhone" placeholder="请输入负责人电话" />
            </el-form-item>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="所辖房产数量">
                        <el-input-number v-model="createForm.propertyNumber" :min="0" :max="99999" />
                    </el-form-item>
                </el-col>
                <el-col :span="4"><el-text type="info" size="small">0~99999</el-text></el-col>
            </el-row>
            <el-form-item label="父级">
                <el-cascader v-model="createForm.parentId" :options="orgData" :props="cascaderProps"
                    placeholder="请选择父级（置空为顶级）" clearable />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="createForm.status" placeholder="请选择状态">
                    <el-option label="启用" value=1 />
                    <el-option label="禁用" value=0 />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="createDialog = false">取消</el-button>
                <el-button type="primary" @click="createOrg">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 编辑区块的弹出层 -->
    <el-dialog v-model="editDialog" title="编辑组织" width="32%">
        <el-form :model="editForm">
            <el-form-item label="组织名称">
                <el-input v-model="editForm.name" placeholder="请输入组织名称" />
            </el-form-item>
            <el-form-item label="组织负责人">
                <el-input v-model="editForm.dutyPersonName" placeholder="请输入负责人名称" />
            </el-form-item>
            <el-form-item label="负责人电话">
                <el-input v-model="editForm.dutyPersonPhone" placeholder="请输入负责人电话" />
            </el-form-item>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="所辖房产数量">
                        <el-input-number v-model="editForm.propertyNumber" :min="0" :max="99999" />
                    </el-form-item>
                </el-col>
                <el-col :span="4"><el-text type="info" size="small">0~99999</el-text></el-col>
            </el-row>


            <el-form-item label="父级">
                <el-cascader v-model="editForm.parentId" :options="orgData" :props="cascaderProps"
                    placeholder="请选择父级（置空为顶级）" clearable />

            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="editForm.status" placeholder="请选择状态">
                    <el-option label="启用" value=1 />
                    <el-option label="禁用" value=0 />
                </el-select>
            </el-form-item>

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialog = false">取消</el-button>
                <el-button type="primary" @click="editOrg">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style>
.header {
    margin-bottom: 7px;
}
</style>